<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>图像分类器</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body {
            background-color: #f8f9fa;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        .header {
            background: linear-gradient(135deg, #6a11cb 0%, #2575fc 100%);
            color: white;
            padding: 2rem 0;
            margin-bottom: 2rem;
            border-radius: 0 0 20px 20px;
        }
        .card {
            border-radius: 15px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.08);
            border: none;
            margin-bottom: 20px;
        }
        .nav-pills .nav-link.active {
            background-color: #6a11cb;
            border-radius: 20px;
        }
        .nav-pills .nav-link {
            color: #495057;
            border-radius: 20px;
        }
        .preview-container {
            width: 100%;
            height: 250px;
            border: 2px dashed #dee2e6;
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            overflow: hidden;
            margin-bottom: 20px;
            background-color: #f8f9fa;
        }
        .preview-container img {
            max-width: 100%;
            max-height: 100%;
            object-fit: contain;
        }
        .btn-primary {
            background: linear-gradient(135deg, #6a11cb 0%, #2575fc 100%);
            border: none;
            border-radius: 20px;
            padding: 10px 25px;
        }
        .result-item {
            padding: 12px 15px;
            margin-bottom: 10px;
            border-radius: 10px;
            background-color: #f8f9fa;
            transition: transform 0.2s;
        }
        .result-item:hover {
            transform: translateX(5px);
            background-color: #e9ecef;
        }
        .progress {
            height: 10px;
            border-radius: 5px;
            margin-top: 5px;
        }
        .loading {
            display: none;
            text-align: center;
            padding: 20px;
        }
        .result-area {
            display: none;
        }
        footer {
            margin-top: 30px;
            padding: 20px 0;
            text-align: center;
            color: #6c757d;
        }
    </style>
</head>
<body>
    <div class="header text-center">
        <div class="container">
            <h1 class="display-4 fw-bold">图像分类器</h1>
            <p class="lead">使用ResNet50模型对图像内容进行分类识别</p>
        </div>
    </div>

    <div class="container">
        <div class="row justify-content-center">
            <div class="col-lg-10">
                <div class="card">
                    <div class="card-body">
                        <ul class="nav nav-pills mb-4 justify-content-center" id="inputMethodTab" role="tablist">
                            <li class="nav-item" role="presentation">
                                <button class="nav-link active" id="url-tab" data-bs-toggle="pill" data-bs-target="#url" type="button" role="tab">图片URL</button>
                            </li>
                            <li class="nav-item" role="presentation">
                                <button class="nav-link" id="upload-tab" data-bs-toggle="pill" data-bs-target="#upload" type="button" role="tab">上传图片</button>
                            </li>
                        </ul>
                        
                        <div class="tab-content" id="inputMethodTabContent">
                            <!-- URL输入 -->
                            <div class="tab-pane fade show active" id="url" role="tabpanel">
                                <div class="mb-3">
                                    <label for="imageUrl" class="form-label">图片URL地址</label>
                                    <input type="text" class="form-control" id="imageUrl" placeholder="https://example.com/image.jpg">
                                </div>
                                <div class="preview-container" id="urlPreview">
                                    <span class="text-muted">图片预览区</span>
                                </div>
                                <div class="d-grid gap-2">
                                    <button class="btn btn-primary" onclick="predictFromUrl()">开始识别</button>
                                </div>
                            </div>
                            
                            <!-- 文件上传 -->
                            <div class="tab-pane fade" id="upload" role="tabpanel">
                                <div class="mb-3">
                                    <label for="formFile" class="form-label">选择图片文件</label>
                                    <input class="form-control" type="file" id="formFile" accept="image/*">
                                </div>
                                <div class="preview-container" id="uploadPreview">
                                    <span class="text-muted">图片预览区</span>
                                </div>
                                <div class="d-grid gap-2">
                                    <button class="btn btn-primary" onclick="uploadImage()">上传并识别</button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- 加载指示器 -->
                <div class="loading" id="loadingIndicator">
                    <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">加载中...</span>
                    </div>
                    <p class="mt-2">正在处理图像，请稍候...</p>
                </div>
                
                <!-- 结果显示区域 -->
                <div class="card result-area" id="resultArea">
                    <div class="card-header bg-white">
                        <h5 class="card-title mb-0">识别结果</h5>
                    </div>
                    <div class="card-body">
                        <div class="d-flex mb-4">
                            <div class="me-3">
                                <img id="resultImage" src="" alt="Result image" class="rounded" style="max-width: 150px;">
                            </div>
                            <div>
                                <h6>图像来源: <span id="imageOrigin"></span></h6>
                                <p class="text-muted mb-0" id="imageInfo"></p>
                            </div>
                        </div>
                        <h6>分类结果 (Top 5):</h6>
                        <div id="predictionsList"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <footer>
        <div class="container">
            <p>图像分类服务 - 基于ResNet50模型</p>
        </div>
    </footer>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // 图片预览功能
        document.getElementById('imageUrl').addEventListener('input', function() {
            const url = this.value.trim();
            const preview = document.getElementById('urlPreview');
            
            if (url) {
                preview.innerHTML = `<img src="${url}" onerror="this.style.display='none'; preview.innerHTML='<span class=\'text-danger\'>无法加载图片</span>'">`;
            } else {
                preview.innerHTML = '<span class="text-muted">图片预览区</span>';
            }
        });

        document.getElementById('formFile').addEventListener('change', function(e) {
            const file = e.target.files[0];
            const preview = document.getElementById('uploadPreview');
            
            if (file) {
                if (!file.type.match('image.*')) {
                    preview.innerHTML = '<span class="text-danger">请选择图像文件</span>';
                    return;
                }
                
                const reader = new FileReader();
                reader.onload = function(e) {
                    preview.innerHTML = `<img src="${e.target.result}">`;
                };
                reader.readAsDataURL(file);
            } else {
                preview.innerHTML = '<span class="text-muted">图片预览区</span>';
            }
        });

        // 通过URL预测
        async function predictFromUrl() {
            const url = document.getElementById('imageUrl').value.trim();
            if (!url) {
                alert('请输入图片URL');
                return;
            }
            
            // 显示加载指示器
            document.getElementById('loadingIndicator').style.display = 'block';
            document.getElementById('resultArea').style.display = 'none';
            
            try {
                const response = await fetch('/predict', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ image_url: url })
                });
                
                const data = await response.json();
                displayResults(data, url);
            } catch (error) {
                console.error('Error:', error);
                alert('请求失败: ' + error.message);
            } finally {
                document.getElementById('loadingIndicator').style.display = 'none';
            }
        }

        // 上传图片预测
        async function uploadImage() {
            const fileInput = document.getElementById('formFile');
            if (!fileInput.files || fileInput.files.length === 0) {
                alert('请选择要上传的图片');
                return;
            }
            
            const formData = new FormData();
            formData.append('file', fileInput.files[0]);
            
            // 显示加载指示器
            document.getElementById('loadingIndicator').style.display = 'block';
            document.getElementById('resultArea').style.display = 'none';
            
            try {
                const response = await fetch('/upload', {
                    method: 'POST',
                    body: formData
                });
                
                const data = await response.json();
                displayResults(data, URL.createObjectURL(fileInput.files[0]));
            } catch (error) {
                console.error('Error:', error);
                alert('上传失败: ' + error.message);
            } finally {
                document.getElementById('loadingIndicator').style.display = 'none';
            }
        }

        // 显示结果
        function displayResults(data, imageSrc) {
            document.getElementById('resultImage').src = imageSrc;
            document.getElementById('imageOrigin').textContent = data.origin_type === 'url' ? 'URL' : '上传';
            document.getElementById('imageInfo').textContent = `识别出 ${data.predictions.length} 个可能类别`;
            
            const predictionsList = document.getElementById('predictionsList');
            predictionsList.innerHTML = '';
            
            data.predictions.forEach(prediction => {
                const confidence = parseFloat(prediction.confidence);
                const confidencePercent = (confidence * 100).toFixed(2);
                
                const resultItem = document.createElement('div');
                resultItem.className = 'result-item';
                resultItem.innerHTML = `
                    <div class="d-flex justify-content-between">
                        <strong>${prediction.label}</strong>
                        <span>${confidencePercent}%</span>
                    </div>
                    <div class="progress">
                        <div class="progress-bar" role="progressbar" style="width: ${confidencePercent}%;" 
                            aria-valuenow="${confidencePercent}" aria-valuemin="0" aria-valuemax="100"></div>
                    </div>
                `;
                
                predictionsList.appendChild(resultItem);
            });
            
            document.getElementById('resultArea').style.display = 'block';
        }

        // 切换标签时重置表单
        document.getElementById('inputMethodTab').addEventListener('click', function(e) {
            if (e.target.id === 'url-tab') {
                document.getElementById('uploadPreview').innerHTML = '<span class="text-muted">图片预览区</span>';
                document.getElementById('formFile').value = '';
            } else if (e.target.id === 'upload-tab') {
                document.getElementById('imageUrl').value = '';
                document.getElementById('urlPreview').innerHTML = '<span class="text-muted">图片预览区</span>';
            }
        });
    </script>
</body>
</html>